package org.jeecg.chase.common.utils;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.apache.commons.lang.StringUtils;
import org.jeecg.chase.common.base.annotation.Process;
import org.jeecg.chase.common.base.data.BaseData;
import org.jeecg.chase.common.supper.process.CommonProcess;

import java.util.Map;

/**
 * @author leikai
 * @version 1.0
 * @description:
 * @date 2021/08/04/0004 17:59
 */
public class ConditionExpressionUtil {

    public static Boolean needExecute(Object object, Process process) {

        CommonProcess commonProcess = new CommonProcess();
        commonProcess.setConditionExpression(process.conditionExpression());
        return needExecute(object, commonProcess);
    }

    public static Boolean needExecute(Object object, CommonProcess commonProcess) {

        Boolean needExecute = true;

        String conditionExpression = commonProcess.getConditionExpression();

        if (StringUtils.isNotBlank(conditionExpression)) {
            Map map = null;
            if (BaseData.class.isInstance(object)) {
                //当前处理的对象类型为FieldAccess
                BaseData attributeValues = (BaseData) object;
                map = attributeValues.getValueMap();
            } else if (object instanceof Map) {
                map = (Map<String, Object>) object;
            }
            needExecute = (Boolean) execute(conditionExpression, map);
        }
        return needExecute;
    }

    public static Object execute(String conditionExpression, Map env) {
        Expression compiledExp = AviatorEvaluator.compile(conditionExpression, true);
        return compiledExp.execute(env);
    }
}
